﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Xml.Serialization;
namespace XYZshell.Game.CardGameEngine
{
	/// <summary>
	/// 游戏类,整个游戏的根
	/// </summary>
	[Serializable]
	public class Game : GameObject
	{
		public Game()
		{
			Players = new List<Player>();
			Desktops = new List<Desktop>();

		}
		/// <summary>
		/// 游戏中的所以玩家
		/// </summary>
		[XmlArrayItem]
		public List<Player> Players
		{
			get;
			set;
		}
		/// <summary>
		/// 游戏中的桌面
		/// </summary>
		[XmlArrayItem]
		public List<Desktop> Desktops
		{
			get;
			set;
		}
		///// <summary>
		///// 游戏中的牌堆
		///// </summary>
		//public  List<Deck> Decks
		//{
		//    get;
		//    set;
		//}


		/// <summary>
		/// 根据路径查找对象
		/// </summary>
		/// <param name="path">路径</param>
		/// <returns>查找的结果</returns>
		public object Find( string path )
		{
			string[] ps=path.Split( ".".ToArray(), StringSplitOptions.RemoveEmptyEntries );
			GameObject   o=this;
			foreach (string p in ps)
			{
				string mem=p;
				string idx=getPathIndexValue(ref  mem );
				if (idx != null)
				{
					IList r=(IList)o.GetValue( mem );

					MethodInfo minfo=null;
					
					
					int index=0;
					object[] args=null;
					if (int.TryParse( idx, out index ))
					{
						args = new object[] { index };
						minfo= r.GetType().GetMethod( "get_Item" ,new Type[]{index.GetType()});
					}
					else
					{
						args = new object[] { idx };
						minfo = r.GetType().GetMethod( "get_Item", new Type[] { idx.GetType() } );
					}
					object i=  minfo.Invoke( r, args );
					if (i is GameObject)
						o = (GameObject)i;
					else
						return i;

				}
				else
				{

					object  r = o.GetValue(mem );

					if (r is GameObject)
						o = (GameObject)r;
					else
						return r;
				}
				//TODO: 根据路径获得对象
			}
			return o;
		}

		string getPathIndexValue(ref string pathPart )
		{
			Regex rgx=new Regex( @"(?<n>\w+)\[(?<val>.+)\]" );
			if (rgx.IsMatch( pathPart ))
			{
				Match m=rgx.Match( pathPart );
				pathPart = m.Result( "${n}" );
				return m.Result( "${val}" ).Trim( "\"".ToArray() );
				;
			}
			
			return null;
		}
		///// <summary>
		///// 
		///// </summary>
		///// <param name="path"></param>
		///// <returns></returns>
		//public  object  FindOne( string path )
		//{
		//    return ((IList)Find( path ))[0];
		//}
	}
}
